import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Popconfirm, Table } from 'antd';
import { Dayjs } from 'dayjs';
import Saver from 'file-saver';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import {
  proShiftScheduleInfoDelete,
  proShiftScheduleInfoExport,
  proShiftScheduleInfoPage
} from '@/services/bizApi/shengchanpaibanjiekou';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProShiftScheduleInfoEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, monthTime, ...formData }) => {
      const [month, monthEnd] = ((monthTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );
      const res = await proShiftScheduleInfoPage({
        ...formData,
        ...id,
        month,
        monthEnd,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="monthTime">
          <DatePicker.RangePicker picker="month" placeholder={['排班月份', '排班月份']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '排班月份',
            dataIndex: 'month'
          },
          {
            title: '班制名称',
            dataIndex: 'shiftSystemName'
          },
          {
            title: '排班名称',
            dataIndex: 'name'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={async () => {
                        const res = await proShiftScheduleInfoExport(
                          {
                            id: row?.id as unknown as string
                          },
                          {
                            skipErrorHandler: true,
                            responseType: 'blob'
                          }
                        );
                        // 获取文件名
                        // const contentDisposition = res.headers['content-disposition'];
                        // let filename = '';

                        // if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
                        //   const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        //   const matches = filenameRegex.exec(contentDisposition);
                        //   if (matches !== null && matches[1]) {
                        //     filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
                        //   }
                        // }

                        Saver.saveAs(res?.data, row?.name + '.xlsx');
                      }}
                      type="primary"
                    >
                      导出
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}

                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除吗？`}
                      onConfirm={async () => {
                        const res = await proShiftScheduleInfoDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
    </>
  );
};

export default Page;
